﻿using Common;
using DeliveryManage.Models;
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Mvc;

namespace DeliveryManage.Filter
{
    public class CustomErrorAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 全局页面控制器异常记录
        /// </summary>
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            ErrorMessage msg = new ErrorMessage(filterContext.Exception, "Page");
            msg.ShowException = MvcException.IsExceptionEnabled();

            //错误记录
            LogHelper.WriteLogFile(JsonHelper.ObjectToJSON(msg), "PageError");
            //设置为true阻止golbal里面的错误执行
            filterContext.ExceptionHandled = true;
            filterContext.Result = new ViewResult() { ViewName = "/Views/ErrorPage/ISE.cshtml", ViewData = new ViewDataDictionary<ErrorMessage>(msg) };

        }
    }

    /// <summary>
    /// 全局API异常记录
    /// </summary>
    public class ApiHandleErrorAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            base.OnException(filterContext);

            //异常信息
            ErrorMessage msg = new ErrorMessage(filterContext.Exception, "Api");
            //接口调用参数
            msg.ActionArguments = JsonHelper.ObjectToJSON(filterContext.ActionContext.ActionArguments);
            msg.ShowException = MvcException.IsExceptionEnabled();

            //错误记录
            LogHelper.WriteLogFile(JsonHelper.ObjectToJSON(msg), "ApiError");
            var content = new
            {
                status = false,
                code = 400,
                msg = "对不起，请求异常。请稍后再试!",
                data = ""
            };
            filterContext.Response = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(JsonHelper.ObjectToJSON(content)) };
        }
    }

    /// <summary>
    /// 异常信息显示
    /// </summary>
    public class MvcException
    {
        /// <summary>
        /// 是否已经获取的允许显示异常
        /// </summary>
        private static bool HasGetExceptionEnabled = false;

        private static bool isExceptionEnabled;

        /// <summary>
        /// 是否显示异常信息
        /// </summary>
        /// <returns>是否显示异常信息</returns>
        public static bool IsExceptionEnabled()
        {
            if (!HasGetExceptionEnabled)
            {
                isExceptionEnabled = true;//不显示异常信息
                HasGetExceptionEnabled = true;
            }
            return isExceptionEnabled;
        }
    }

}